package com.adee.gulimall.search.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 测试csrf攻击，该controller为受信网站服务
 */
@Slf4j
@Controller
@RequestMapping("/csrf/test")
public class CsrfTestController {

    @GetMapping("/test")
    public String test(HttpServletRequest req, HttpServletResponse resp) {
        Cookie[] cookies = req.getCookies();
        if(cookies != null) {
            for (Cookie c : cookies) {
                log.info("{}:{}:{}:{}", c.getDomain(), c.getPath(), c.getName(), c.getValue());
            }
        }

        return "index";
    }

    // 登录
    @GetMapping("/login")
    public String login(HttpServletRequest req, HttpServletResponse resp) {
        Cookie c = new Cookie("login_token", "123456");
        c.setPath("/");
        resp.addCookie(c);

        return "index";
    }

    // 登出
    @GetMapping("/logout")
    public String logout(HttpServletRequest req, HttpServletResponse resp) {
        Cookie c = new Cookie("login_token", "");
        c.setPath("/");
        c.setMaxAge(0); // 设置cookie超时时间0，即马上过期，等效于告诉浏览器立即删除cookie
        resp.addCookie(c);

        return "index";
    }

    // 模拟转账操作
    @GetMapping("/transfer")
    public String transfer(HttpServletRequest req, HttpServletResponse resp) {
        Cookie[] cs = req.getCookies();
        if(cs == null) {
            return "login";
        }
        boolean hasLogin = false;
        for (Cookie c : cs) {
            if ("login_token".equals(c.getName()) && "123456".equals(c.getValue())) {
                hasLogin = true;
                break;
            }
        }
        if (!hasLogin) {
            return "login";
        }
        String from = req.getParameter("from");
        String to = req.getParameter("to");
        String amount = req.getParameter("amount");
        log.info("[{}]向[{}]转账{}元", from, to, amount);

        return "index";
    }
}
